#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
const int MAXN = 2e5 + 10;

int t, n, a[MAXN], b[MAXN];
int tr[MAXN];

inline int lowbit(int x) {
    return x & (-x);
}

int sum(int k) {
    int res = 0;
    while (k) {
        res += tr[k];
        k -= lowbit(k);
    }
    return res;
}

void add(int k, int d = 1) {
    while (k <= n) {
        tr[k] += d;
        k += lowbit(k);
    }
}

void discrete() {
    for (int i = 1;i <= n;i++)
        b[i] = a[i];

    sort(b + 1, b + n + 1);
    int m = unique(b + 1, b + n + 1) - b - 1;
    for (int i = 1;i <= n;i++) {
        a[i] = lower_bound(b + 1, b + m + 1, a[i]) - b;
    }
}


int main() {
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
#endif
    ios::sync_with_stdio(false), cin.tie(0);

    cin >> t;
    while (t--) {
        cin >> n;
        for (int i = 1; i <= n; i++) cin >> a[i];

        discrete();
        ll res = 0;
        for (int i = 1; i <= n; i++) {
            int left = sum(a[i] - 1);
            int right = i-1 - sum(a[i]);

            res += min(left, right);
            add(a[i], 1);
        }

        for (int i = 1; i <= n; i++) add(a[i], -1);
        cout << res << endl;
    }
}